<template>  
    <div class="addAsset">
        <ul class="tabList">
            <li v-for="(item,index) in tabList" :key="index" :class="{active:index == $store.state.activeIndex}" @click="tabLiChange(index,true)">{{item.key}}</li>
            <li v-if="id" class="updateLi">
                <div @click="goBack"><i class="el-icon-arrow-left"></i><span style="font-weight:400">返回</span></div><p>资产编辑</p>
            </li>
        </ul>
        <div style="padding:20px 10px 40px;overflow:hidden;" v-show="$store.state.activeIndex == 0 || id">
            <!-- 单个新增 -->
            <el-form ref="form" :model="form" :rules="formRules" label-width="100px" :inline="true" size='medium'  @submit.native.prevent>
                        <el-form-item label="资产名称" prop="f_name" >
                            <el-input v-model="form.f_name" placeholder="请输入资产名称" maxlength="20"></el-input>
                        </el-form-item>
                        <el-form-item label="资产编码" prop="f_code" >
                            <el-input v-model="form.f_code" placeholder="请输入资产名称" maxlength="20"></el-input>
                        </el-form-item>
                        <el-form-item label="资产分类" prop="f_cid" >
                            <el-select v-model="form.f_cid" placeholder="请输入资产类别" >
                                <el-option-group v-for="group in assetClassOption" :key="group.id" :label="group.category_name">
                                    <el-option v-for="item in group.cate" :key="item.id" :label="item.category_name" :value="item.id">
                                    </el-option>
                                </el-option-group>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="计量单位" prop="f_unit">
                            <el-input v-model="form.f_unit" placeholder="请输入单位" maxlength="10"></el-input>
                        </el-form-item>
                        <el-form-item label="选择仓库" prop="wh_id">
                            <el-select  v-model="form.wh_id"  placeholder="请选择仓库" disabled>
                                <el-option v-for="item in warehouseOptions" :key="item.wh_id" :label="item.wh_name" :value="item.wh_id" ></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="单价" prop="f_unit_price">
                            <el-input v-model="form.f_unit_price" placeholder="请输入金额" maxlength="10" ></el-input>
                        </el-form-item>
                        <el-form-item label="来源" prop="f_supplier">
                            <el-input v-model="form.f_supplier" placeholder="请输入来源" maxlength="10" ></el-input>
                        </el-form-item>
                        <el-form-item label="品牌名称" prop="f_brand">
                            <el-input v-model="form.f_brand" placeholder="请输入资产品牌" maxlength="20"></el-input>
                        </el-form-item>
                        <el-form-item label="采购时间" prop="f_purchase_date">
                            <el-date-picker type="date" value-format="yyyy-MM-dd" placeholder="请选择采购时间" v-model="form.f_purchase_date" ></el-date-picker>
                        </el-form-item>

                        <el-form-item label="入库时间" prop="f_storage_date">
                            <el-date-picker type="date" value-format="yyyy-MM-dd" placeholder="请选择入库时间" v-model="form.f_storage_date"  ></el-date-picker>
                        </el-form-item>
                        <el-form-item label="型号" prop="f_specs">
                            <el-input v-model="form.f_specs" placeholder="请输入资产型号" maxlength="20"></el-input>
                        </el-form-item>
                        <el-form-item label="保修年限"  prop="f_guarantee_years">
                                <el-input v-model.number="form.f_guarantee_years" placeholder="请输入保修年限" maxlength="20"></el-input>
                        </el-form-item>
                        <el-form-item label="采购人"  prop="f_purchase_name">
                                <el-input v-model="form.f_purchase_name" placeholder="请输入采购人" maxlength="20"></el-input>
                        </el-form-item>
                        <el-form-item label="使用年限" prop="f_use_years">
                            <el-input v-model.number="form.f_use_years" placeholder="请输入使用年限" maxlength="20"></el-input>
                        </el-form-item>
                        <el-form-item label="入库数量" prop="f_num" v-if="!$route.query.id"> 
                            <el-input v-model.number="form.f_num" placeholder="请输入入库数量" maxlength="20"></el-input>
                        </el-form-item>  
                        <div>
                            <el-form-item label="图片" prop="f_image_url">
                            <ul class="mainlist">
                                    <li v-for="(list,index) in form.f_image_url" :key="index" @mouseenter="list.delshow=true"  @mouseleave="list.delshow=false" >
                                        <img class="img" :src="list.image_url" alt="" width="70px" height="70px">
                                        <div class="delpic" v-if="list.delshow" >
                                            <i @click.stop="delcouPicHan(list,index)" class="el-icon-delete ii"></i> 
                                            <i @click.stop="dialogImageUrl=list.image_url;dialogVisible=true;" class="el-icon-zoom-in ii"></i> 
                                        </div>
                                    </li>
                                    <li  @click.stop="upcouPic(2)" v-loading.fullscreen.lock="fullscreenLoading">
                                        <i style="font-size:40px;color:rgb(217,217,217);font-weight:600" class="el-icon-plus"></i>
                                        <!-- <span style="font-size:50px;color:rgb(217,217,217)">+</span>     -->
                                    </li>
                                </ul>
                                <div class="addfix">图片尺寸为正方形，最多上传6张，只支持.jpg 格式。</div>
                            </el-form-item>
                        </div>
                        <el-form-item >
                            <el-button style="margin-left:80px" type="primary" @click="onSubmit" v-loading.fullscreen.lock="fullscreenLoading">保存</el-button>
                            <el-button @click="reset">重置</el-button>
                        </el-form-item>
                        <div class="tip">当<span>【入库数量】</span>大于2时，会自动生成两个独立的资产，相同的资产无需重复输入。编码会自动在后面生成-1或-2</div>
            </el-form>
        </div>
        <div style="padding:20px 10px 40px;overflow:hidden;" v-show="$store.state.activeIndex == 1">
            批量新增
            <!-- 批量新增 -->
        </div>
        <!-- 图片预览 -->
        <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
    </div>
</template>

<script>
 /* eslint-disable */ 
import fileUtil from '@/libs/fileUtil.js'
import moment from 'moment'
import OSS from 'ali-oss'
import {getCategoriesApi,getRam } from "@/api" 
import {addAssetsApiFn,getAssetsInfoApi,updateAssetsApiFn} from "../api" 
export default {
    name:"formvue",
    props: {
        id:{
            type:[Number,String],
            default:null
        }
    },
    data(){
        /**数字验证 */
        var checkNumber = (rule, value, callback)=>{
            if (!value) {
                return callback(new Error('使用年限必须大于零'));
            } else {
                const reg = /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/
                if (reg.test(value)) {
                    callback();
                } else {
                    return callback(new Error('请输入大于0的数字'));
                }
            }
        };
        return{
            fullscreenLoading:false,
            dialogVisible:false,/**显示预览图片 */
            dialogImageUrl:'',/**预览图片url */
            statusOption:[],/**所有状态 */
            warehouseOptions:[],/**所有仓库 */
            assetClassOption:[],
            form:{
                f_image_url:[],
                f_cid:'',
                f_name:'',
                f_supplier:'',
                f_code:'',
                f_unit:'',
                wh_id:'',
                f_specs:'',
                f_use_years:'',
                f_brand:'',
                f_unit_price:'',
                f_purchase_date:'',
                f_num:'',
                f_purchase_name:'',
                f_storage_date:'',
                f_guarantee_years:'',
            },
            formRules: {
                f_name: [ { required: true, message: '资产名称不能为空', trigger: 'blur' }],/*资产名称的校验*/
                f_code:[ { required: true, message: '资产编码不能为空', trigger: 'blur' }],/*资产编码的校验*/
                f_unit:[ { required: true, message: '计量单位不能为空', trigger: 'blur' }],/*资产计量单位的校验*/
                f_cid: [{ required: true, message: '请选择资产类别', trigger: 'blur' }],/*资产类别的校验*/
                wh_id: [{ required: true, message: '请选择仓库', trigger: 'blur' }],/*仓库的的校验*/
                f_unit: [{ required: true, message: '单位不能为空', trigger: 'blur' }],/*单位的校验*/
                // f_use_years: [
                //     { required: true, message: '使用年限不能为空', trigger: 'blur' },
                //     { type: 'number', message: '使用年限必须为数字' },
                //     {validator: checkNumber, trigger: 'blur'}
                // ],/*使用年限的校验*/
                // f_brand:[ { required: true, message: '品牌名称不能为空', trigger: 'blur' }],/*资产名称的校验*/
                f_unit_price: [
                    // { required: true, message: '金额不能为空', trigger: 'blur' },
                    // {validator: checkNumber, trigger: 'blur'}
                ],/*金额的校验*/
                // f_num:[ { required: true,type:'number', message: '入库数量不能为空', trigger: 'blur' }],/*入库数量的校验*/
                // f_purchase_name:[ { required: true, message: '采购人不能为空', trigger: 'blur' }],/*采购人的校验*/
                // f_specs:[ { required: true, message: '型号不能为空', trigger: 'blur' }],/*资产名称的校验*/
                // f_guarantee_years: [{ type: 'number', required: true, message: '请输入保修年限', trigger: 'blur' }],/*保修年限的校验*/
                // f_image_url:[{ type: 'array', required: true, message: '请上传图片', trigger: 'change' }],/*保修年限的校验*/
            },
            tabList:[]
        }
    },
    created(){
        this.getClassData()
        if(this.id){
            getAssetsInfoApi({id:this.id}).then(res=>{
                res.image&&res.image.length?res.image.forEach(element => {
                    element.delshow = false
                }):''
                this.form = {
                    f_image_url:res.image,
                    f_cid:res.f_cid,
                    f_name:res.f_name,
                    f_code:res.f_code,
                    f_supplier:res.f_supplier,
                    f_unit:res.f_unit,
                    wh_id:res.wh_id,
                    f_specs:res.f_specs,
                    f_use_years:res.f_use_years,
                    f_brand:res.f_brand,
                    f_unit_price:res.f_unit_price,
                    f_num:res.f_num,
                    f_purchase_name:res.f_purchase_name,
                    f_purchase_date:res.f_purchase_date,
                    f_storage_date:res.f_storage_date,
                    f_guarantee_years:res.f_guarantee_years,
                }
            })
        }else{
            this.$store.commit('setactiveIndex',0)
            this.tabList = [
                {
                    key:'单个新增'
                },
                {
                    key:'批量新增'
                }
            ]
        }
    },
    methods: {
        goBack(){
            this.$emit('close',false)
        },
        tabLiChange(index,status = false){
           this.$store.commit('setactiveIndex',index)
        },
        /**获取全部资产分类 */
        getClassData(){
            this.warehouseOptions = this.$store.state.myWarehouse
            log(this.warehouseOptions,this.$store.state.warehouseOfAssetsManager)
            this.form.wh_id = this.$store.state.warehouseOfAssetsManager
            this.form.f_cid = ''
            getCategoriesApi({category_type:2,wh_id:this.$store.state.warehouseOfAssetsManager}).then(res=>{
                this.assetClassOption = res
            })
        },
        /**创建新资产 */
        onSubmit(){
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    let params = JSON.parse(JSON.stringify(this.form))
                    params.f_image_url = JSON.stringify(params.f_image_url)
                   if(this.id){ /**编辑 */
                       params.id = this.id
                       if('f_num' in params) delete params.f_num
                       updateAssetsApiFn(params).then(res=>{
                           let that = this
                           this.$emit('close',false)
                       })
                   }else{ /**新增 */
                       addAssetsApiFn(params).then(res=>{
                           this.$store.commit('setactiveIndex',0)
                           this.$refs['form'].resetFields();
                       })
                   }

                }
            });
        },
         //删除图片
        delcouPicHan(list,index){
            this.form.f_image_url.splice(index, 1)
        },
        //图片上传
        upcouPic(val){
            if(this.form.f_image_url.length<6){
                fileUtil.getFile({
                    multiple:true,
                    aaccept:"image/jpg,image/png", //文件类型， 非必填，默认值image/*
                    done:(files,src,dom)=>{
                        var file = Array.prototype.slice.call(files) 
                        let _this =this;
                        getRam().then(res=>{
                            var client = new OSS({
                                region: res.region,
                                accessKeyId: res.accessKeyId,
                                accessKeySecret: res.accessKeySecret,
                                bucket:  res.bucket
                            });
                            let arr = []
                            for(let i=0;i<file.length;i++){ /**循环上传 */
                                if(this.form.f_image_url.length+i>=6){
                                    this.$message.warning(`当前限制选择 6 个文件，请将不要的附件先进行删除`);
                                    break
                                } 
                                this.fullscreenLoading = true
                                if(file[i].type.indexOf('image')>-1){
                                    let promise = client.multipartUpload((new Date().getTime())+file[i].name, file[i]).then(function(respond){
                                    let obj = {image_url:res.url+respond.name,delshow:false}
                                    _this.form.f_image_url.push(obj)
                                    }).catch((err) => {
                                        log(2222,err)
                                    })
                                    arr.push(promise)
                                }else{
                                return Toast('文件格式不对');
                                }
                            }
                            Promise.all(arr).then((result) => {
                                this.fullscreenLoading = false
                            }).catch(err=>{
                                this.fullscreenLoading = false
                            })
                        })
                    }
                })
            }else{
                this.$message.warning(`当前限制选择 6 个文件，请将不要的附件先进行删除`);
            }
        },
        /**重置 */
        reset(){
            this.$refs['form'].resetFields();
        }
    },
}
</script>

<style lang="stylus" scoped>
.addAsset
    background-color #FFFFFF
    padding 0 0 40px 0
    border: 1px solid rgba(224, 227, 234, 1);width:clac(100% - 2px)
    .tabList
        list-style-type none
        width 100%
        height 50px
        background-color rgba(243, 246, 249, 1)
        border-radius 5px 5px 0px 0px
        border-bottom: 1px solid rgba(224, 227, 234, 1)
        // border-left none
        display flex
        li
           width 130px
           height 50px
           line-height 50px
           text-align center
           font-size 14px
           color #606266
           font-weight 600
           cursor pointer
           &:last-child
             border-right 1px solid rgba(224, 227, 234, 1)
             border-radius 5px 5px 0px 0px
           &:first-child
             border-left none !important
             border-radius 5px 5px 0px 0px
        .updateLi
            border:none !important
            text-align left
            width 300px
            display flex
            align-items center
            padding-left 22px
            i,span
               color #198AFA
            i
               font-weight 600
               padding-right 3px
            span
               padding-right 10px
        .active
           color rgba(56, 148, 255, 1);
           background-color #fff
           border-radius 5px 5px 0px 0px
           padding-bottom 1px
           border-right 1px solid rgba(224, 227, 234, 1)
           border-left 1px solid rgba(224, 227, 234, 1)
    .mainlist
        display: flex
        li
            width 70px
            position relative
            height 70px
            cursor pointer
            margin 10px 10px 10px 0
        li:last-child 
            width 64px
            height 64px
            display flex
            align-items center
            justify-content center
            border 3px  dashed  rgb(217,217,217)
        .delpic
            height 70px;
            background rgba(0,0,0,0.5)
            position absolute
            display flex
            justify-content space-around
            align-items center
            right 0
            bottom 0
            z-index 100
            width: 70px;
            line-height 64px
            color #fff
            font-size 30px
    .addfix
        color: rgba(0, 0, 0, 0.45);
        font-size: 12px;
    .tip
        color #A6A3A3
        font-size 12px
        margin-left 80px
        >span 
            color rgb(237,80,90)
            font-size 12px

               
</style>
<style lang="stylus">
.addAsset
    // .el-select>.el-input
    //     width 206.4px
    // .el-date-editor.el-input, .el-date-editor.el-input__inner
    //     width 206.4px
    .el-input--medium
        width 206.4px

</style>
